package com.joshua.spring.integration.exception;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.joshua.spring.entity.vo.ErrorMsg;
import com.joshua.spring.entity.vo.GlobalResponse;
import com.joshua.spring.util.JacksonUtils;

import java.io.IOException;

/**
 * com.joshua.spring.business.integration.exception -- IntegrationExceptionSerializer
 * description:
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/1/8 10:39
 */
public class IntegrationExceptionSerializer extends StdSerializer<IntegrationException> {

    public IntegrationExceptionSerializer() {
        super(IntegrationException.class);
    }

    /**
     * description: 序列化的内容可以使用下面的内容替换
     * <p>
     * jsonGenerator.writeStartObject();
     * jsonGenerator.writeNumberField("code", e.getHttpErrorCode());
     * jsonGenerator.writeBooleanField("status", false);
     * jsonGenerator.writeObjectField("data", null);
     * jsonGenerator.writeObjectField("msg", Arrays.asList(value.getOAuth2ErrorCode(),value.getMessage()));
     * if (value.getAdditionalInformation()!=null) {
     * for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
     * String key = entry.getKey();
     * String add = entry.getValue();
     * jsonGenerator.writeStringField(key, add);
     * }
     * }
     * jsonGenerator.writeEndObject();
     *
     * @param e                  {@link IntegrationException}
     * @param jsonGenerator      {@link JsonGenerator}
     * @param serializerProvider {@link SerializerProvider}
     * @throws IOException
     * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
     * @date 2020/1/8 10:47
     */
    @Override
    public void serialize(IntegrationException e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        //输出自定义字符串
        GlobalResponse responseVO = new GlobalResponse();
        if (e.getAdditionalInformation() != null) {
            responseVO.setData(e.getAdditionalInformation());
        }
        responseVO.setCode(e.getCode());
        responseVO.setErrorMsg(ErrorMsg.builder().eMsg(e.getMessage()).build());
        jsonGenerator.writeRawValue(JacksonUtils.obj2json(responseVO));
    }
}
